import indexedDB from "@/services/index";

// 添加文章
export const addArticle = async (article: Article) => {
  await indexedDB.updateData("articles", article, "add");
};

// 获取所有文章
export const getAllArticles = async (includeDeleted = false) => {
  const result = await indexedDB.getData("articles");
  return (result as ArticleWithId[])
    .filter((a) => includeDeleted || !a.is_deleted)
    .sort((a, b) => b.updateTime - a.updateTime);
};

// 更新文章
export const updateArticle = async (article: ArticleWithId) => {
  await indexedDB.updateData("articles", article, "put");
};

// 删除文章
export const deleteArticle = async (id: string) => {
  await indexedDB.deleteData("articles", id);
};

// 清空文章存储区
export const clearArticles = async () => {
  await indexedDB.deleteData("articles");
};

// 根据 ID 获取单个文章
export const getArticleById = async (
  id: string
): Promise<ArticleWithId | undefined> => {
  const article = await indexedDB.getData("articles", id);
  return article as ArticleWithId | undefined;
};

// 新增软删除方法
export const softDeleteArticle = async (id: string) => {
  const article = await getArticleById(id);
  if (article) {
    article.is_deleted = 1;
    article.delete_time = Date.now();
    await updateArticle(article);
  }
};

// 新增恢复方法
export const restoreArticle = async (id: string) => {
  const article = await getArticleById(id);
  if (article) {
    article.is_deleted = 0;
    delete article.delete_time;
    return updateArticle(article);
  }
};

const AUTO_DELETE_DAYS = 30;

const checkExpiredArticles = async () => {
  const articles = await getAllArticles(true);
  const expired = articles.filter(
    (a) =>
      a.is_deleted &&
      Date.now() - (a.delete_time || 0) > AUTO_DELETE_DAYS * 86400000
  );

  await Promise.all(expired.map((a) => deleteArticle(a.id)));
};

// 每天检查一次
setInterval(checkExpiredArticles, 86400000);

// 新增回收站相关方法
export const getDeletedArticles = async () => {
  return indexedDB.getDataByIndex("articles", "is_deleted", 1);
};

export const emptyRecycleBin = async () => {
  const deleted = await getDeletedArticles();
  return Promise.all(deleted.map((a) => deleteArticle(a.id)));
};

export const deleteArticlePermanently = async (id: string) => {
  await indexedDB.deleteData("articles", id);
  await deleteArticleHistory(id); // 删除关联的历史记录
};
